# -*- coding:utf-8 -*-
"""
运行，执行

"""
from django.conf import settings
# from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver import Remote
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time, os, json, string, datetime
import logging, traceback

from Apps.UITest.models import uiCaseLog
from Apps.UITest.uiSelenium.driverWork import DriverWork
from Apps.UITest.uiSelenium.element import Element
from Apps.UITest.uiSelenium.action import Actions

logger = logging.getLogger('django')


class Runner:
    def __init__(self, caseDate, UiTestId):
        self.driver = Remote(command_executor=settings.DRIVER_HUB,
                                desired_capabilities=DesiredCapabilities.CHROME)
        self.vars = {}

        self.caseDate = json.loads(caseDate)
        self.ele = Element(self.driver)
        self.tests = self.caseDate["tests"]
        logger.info(UiTestId)
        # self.caseLogInstance = caseLogInstance
        self.caseLogInstance = uiCaseLog.objects.get(id=UiTestId)
        self.caseLogInstance.session_id = self.driver.session_id
        self.caseLogInstance.capabilities = self.driver.capabilities
        self.caseLogInstance.browserName = self.driver.capabilities["browserName"]
        self.caseLogInstance.browserVersion = self.driver.capabilities["browserVersion"]
        self.caseLogInstance.platformName = self.driver.capabilities["platformName"]
        self.caseLogInstance.run_case_data_tests = self.caseDate["tests"]
        self.start_time = datetime.datetime.now()
        self.caseLogInstance.start_time = self.start_time
        self.caseLogInstance.status = "2"
        self.caseLogInstance.save()

        for test in self.tests:
            self.testId = test.get('id', '')
            self.testUrl = test.get('url', '')
            self.testName = test.get('name', '')
            logger.info(self.testName)
            self.testCommands = test.get('commands', '')

            if not os.path.exists(os.path.join(settings.BASE_DIR, "static", "file", self.testId)):
                os.makedirs(os.path.join(settings.BASE_DIR, "static", "file", self.testId))

            for testCommand in self.testCommands:
                self.testCommandId = testCommand.get("id", '')
                logger.info(self.testCommandId)
                self.testCommandComment = testCommand.get("comment", '')
                self.testCommandCommand = testCommand.get("command", '')
                self.testCommandTarget = self.template(testCommand.get("target", ''))
                self.testCommandTargets = testCommand.get("targets", '')
                self.testCommandValue = self.template(testCommand.get("value", ''))
                self.testOpensWindow = testCommand.get("opensWindow", None)
                self.testWindowHandleName = testCommand.get("windowHandleName", None)
                self.testWindowTimeout = testCommand.get("windowTimeout", None)

                self.caseLogInstance.current_test_id = self.testCommandId
                self.caseLogInstance.save()

                # 运行用例
                self.run()

        self.end_time = datetime.datetime.now()
        self.caseLogInstance.end_time = self.end_time
        self.caseLogInstance.elapsed_time = self.end_time - self.start_time
        self.caseLogInstance.is_success = "2"
        self.caseLogInstance.status = "3"
        self.caseLogInstance.save()

        #     执行结束,关闭浏览器
        self.driver.quit()

    def run(self):

        time.sleep(0.5)

        try:
            if self.testCommandCommand in ["assert", "else", "if", "run", "while"]:
                self.testCommandCommand = self.testCommandCommand.title
            if hasattr(self, self.testCommandCommand):
                getattr(self, self.testCommandCommand)()
        except Exception as e:

            logger.info(self.testCommandId)
            logger.info(traceback.format_exc(limit=2, chain=False))
            self.caseLogInstance.error_message = str(e)
            self.caseLogInstance.is_success = "3"
            self.caseLogInstance.status = "3"
            self.caseLogInstance.current_test_id = ''
            self.caseLogInstance.save()
            # 执行错误，关闭浏览器
            self.driver.quit()

    # ##########################   工具方法   ###############################
    def wait_for_window(self, timeout=2):
        """
        等待Windows打开
        :param timeout:
        :return:
        """
        time.sleep(round(timeout / 1000))
        wh_now = self.driver.window_handles
        wh_then = self.vars["window_handles"]
        if len(wh_now) > len(wh_then):
            return set(wh_now).difference(set(wh_then)).pop()

    def template(self, testStr):
        """
        模版替换${}
        :return:
        """
        return string.Template(testStr).safe_substitute(self.vars)

    # ##########################   命令方法   ###############################
    def addSelection(self):
        pass

    def answerOnNextPrompt(self):
        pass

    def Assert(self):
        """
         {
          "id": "dc00ed01-eb5c-4a7b-a63e-28025f3272a6",
          "comment": "",
          "command": "assert",
          "target": "output",
          "targets": [],
          "value": "a"
        }
        output 是变量
        :return:
        """
        """
        关键字：需要大写
        :return:
        """

        if self.vars.get(self.testCommandTarget):
            if self.vars.get(self.testCommandTarget) == self.testCommandValue:
                pass
            else:
                # 校验未通过
                pass
        else:
            # 无该变量
            pass

    def assertAlert(self):
        pass

    def assertChecked(self):
        """
        {
          "id": "e050fea7-ff7f-4a6d-86db-b65e23c66a1f",
          "comment": "",
          "command": "assertChecked",
          "target": "id=f",
          "targets": [],
          "value": ""
        }
        :return:
        """
        pass

    def assertConfirmation(self):
        pass

    def assertEditable(self):
        """
        {
          "id": "a0ebea3d-0705-474f-b4b3-ffbe68fea6ac",
          "comment": "",
          "command": "assertEditable",
          "target": "id=e",
          "targets": [],
          "value": ""
        }
        :return:
        """
        pass

    def assertElementPresent(self):
        """
        {
          "command": "assertElementPresent",
          "target": "css=.lnXdpd",
          "value": "",
          "id": "c3a7876e-3202-4cf2-8cbb-f2561d14fca3",
          "targets": [
            [
              "css=[data-iml=\"1681129024592\"]",
              "css:data-attr"
            ],
            [
              "css=.lnXdpd",
              "css:finder"
            ],
            [
              "xpath=(//img[@alt='Google'])[1]",
              "xpath:img"
            ],
            [
              "xpath=(//img[@id='hplogo'])[1]",
              "xpath:attributes"
            ]
          ]
        }
        :return:
        """
        pass

    def assertElementNotPresent(self):
        pass

    def assertNotChecked(self):
        """
        {
          "id": "449d7cc6-bcfd-43e8-a45d-69578b6a1787",
          "comment": "",
          "command": "assertNotChecked",
          "target": "id=f",
          "targets": [],
          "value": ""
        }
        :return:
        """
        pass

    def assertNotEditable(self):
        """
        {
          "id": "80844f39-aebb-436a-9fd8-e0bebb242b01",
          "comment": "",
          "command": "assertNotEditable",
          "target": "id=d",
          "targets": [],
          "value": ""
        }
        :return:
        """
        pass

    def assertNotSelectedValue(self):
        pass

    def assertNotText(self):
        pass

    def assertPrompt(self):
        pass

    def assertSelectedValue(self):
        """
        {
          "id": "652617a6-f8d7-4e1f-ac38-e9c8f0730ea2",
          "comment": "",
          "command": "assertSelectedValue",
          "target": "id=select",
          "targets": [],
          "value": "1"
        },
        :return:
        """
        pass

    def assertSelectedLabel(self):
        """
        {
          "id": "55847a24-c2e4-481a-b5ff-6e360d370151",
          "comment": "",
          "command": "assertSelectedLabel",
          "target": "id=select",
          "targets": [],
          "value": "One"
        }
        :return:
        """
        pass

    def assertText(self):
        """
        {
          "id": "86a73722-d5a7-4b00-a894-18f59263c8c5",
          "comment": "",
          "command": "assertText",
          "target": "id=a",
          "targets": [
            ["id=a", "id"],
            ["css=#a", "css:finder"],
            ["css=#a", "css"],
            ["xpath=//div[@id='a']", "xpath:attributes"],
            ["xpath=//div", "xpath:position"]
          ],
          "value": "out"
        }
        :return:
        """
        pass

    def assertTitle(self):
        """
        {
          "id": "2a912487-2f0d-4242-bf98-2020ef0194fb",
          "comment": "",
          "command": "assertTitle",
          "target": "Elemental Selenium: Receive a Free, Weekly Tip on Using Selenium like a Pro",
          "targets": [],
          "value": ""
        },
        {
          "id": "17065682-7c81-4906-b2dd-e8a933ad57f4",
          "comment": "",
          "command": "assertTitle",
          "target": "The Internet",
          "targets": [],
          "value": ""
        }
        :return:
        """
        pass

    def assertValue(self):
        """
        {
          "id": "cdbdf862-553c-4366-a183-671a1b95ab94",
          "comment": "",
          "command": "assertValue",
          "target": "id=v",
          "targets": [],
          "value": "sync"
        }
        :return:
        """
        pass

    def check(self):
        """
        <input type="checkbox" id="t" checked />
        <input type="checkbox" id="f" />

        {
          "id": "910b677a-24ba-4c90-879b-799347091085",
          "comment": "",
          "command": "check",
          "target": "id=f",
          "targets": [],
          "value": ""
        }
        :return:
        """
        pass

    def chooseCancelOnNextConfirmation(self):
        pass

    def chooseCancelOnNextPrompt(self):
        pass

    def chooseOkOnNextConfirmation(self):
        pass

    def click(self):
        """
        {
          "id": "aef21113-5b0a-4f32-b2b9-f234bd9097dd",
          "comment": "",
          "command": "click",
          "target": "id=content_left",
          "targets": [
            ["id=content_left", "id"],
            ["css=#content_left", "css:finder"],
            ["xpath=//div[@id='content_left']", "xpath:attributes"],
            ["xpath=//div[@id='container']/div[3]", "xpath:idRelative"],
            ["xpath=//div[4]/div/div[3]", "xpath:position"]
          ],
          "value": ""
        },
        {
          "id": "3dbeb0e1-deb5-4be1-b429-0574094c46d2",
          "comment": "",
          "command": "click",
          "target": "linkText=百度翻译",
          "targets": [
            ["linkText=百度翻译", "linkText"],
            ["css=section:nth-child(1) section:nth-child(1) .c-font-medium", "css:finder"],
            ["xpath=//a[contains(text(),'百度翻译')]", "xpath:link"],
            ["xpath=//div[@id='1']/div/section/div[2]/div/div/section/div/div[2]/a", "xpath:idRelative"],
            ["xpath=(//a[contains(@href, '/s?rsv_idx=1&wd=%E7%99%BE%E5%BA%A6%E7%BF%BB%E8%AF%91&fenlei=256&usm=4&ie=utf-8&rsv_pq=d3e4bb4300002ccf&oq=demo&rsv_t=2062bC1Sc%2F1M1w26Z912RlasL377s%2FeuzFo8IeYTJs7oY4uM47ITIN8K%2FJA&rsv_cq=demo&rsv_dl=0_right_recommends_merge_20826&euri=3ad3768e9ef2410f83541687bde37f7f')])[3]", "xpath:href"],
            ["xpath=//section/div/div[2]/a", "xpath:position"],
            ["xpath=//a[contains(.,'百度翻译')]", "xpath:innerText"]
          ],
          "value": "",
          "opensWindow": true,
          "windowHandleName": "win966",
          "windowTimeout": 2000
        }
        :return:
        """
        by, value = self.testCommandTarget.split("=")
        if hasattr(self.ele, by):
            fun = getattr(self.ele, by)
            targetEle = fun(value)
            Actions(targetEle).click()
        if self.testOpensWindow:
            self.vars[self.testWindowHandleName] = self.wait_for_window(self.testWindowTimeout)

    def clickAt(self):
        pass

    def close(self):
        """
        {
          "id": "d2763b02-1575-4b50-bc55-2838d849ca17",
          "comment": "",
          "command": "close",
          "target": "",
          "targets": [],
          "value": ""
        }
        :param url:
        :return:
        """
        """此命令关闭则关闭了session，浏览器"""
        # self.driver.close()
        pass

    def debugger(self):
        pass

    def do(self):
        pass

    def doubleClick(self):
        pass

    def doubleClickAt(self):
        pass

    def dragAndDropToObject(self):
        pass

    def echo(self):
        """
        {
            "id": "9e61266a-9cb0-49b6-b5bf-a362bd181b58",
          "command": "echo",
          "target": "This is a test string ${number}",
          "value": "",
        }
        :return:
        """
        pass

    def editContent(self):
        pass

    def Else(self):
        """
        {
          "id": "1412686c-5810-419a-993b-7a31cd1cf2ab",
          "comment": "",
          "command": "else",
          "target": "",
          "targets": [],
          "value": ""
        }
        :return:
        """
        """
        关键字：需要大写
        :return:
        """
        pass

    def elseIf(self):
        pass

    def end(self):
        """
        {
          "id": "9cd2ad99-68c3-477c-afd3-20038fdd296c",
          "comment": "",
          "command": "end",
          "target": "",
          "targets": [],
          "value": ""
        }
        :return:
        """
        pass

    def executeScript(self):
        """
        {
          "id": "06a49f39-c64d-48bd-a7e8-b3b592e926fe",
          "comment": "",
          "command": "executeScript",
          "target": "return \"a\"",
          "targets": [],
          "value": "myVar"
        },
        {
          "id": "87d91e6e-369f-4d6e-9869-80feec5e8a1e",
          "comment": "",
          "command": "if",
          "target": "${myVar} === \"a\"",
          "targets": [],
          "value": ""
        },
        {
        "id": "c01d1c80-48af-431f-846a-220086a8d9ee",
        "name": "execute script array",
        "commands": [{
          "id": "4003bbb5-a558-428d-afcc-9feca6bb7204",
          "comment": "",
          "command": "executeScript",
          "target": "return [1,2,3]",
          "targets": [],
          "value": "x"
        },
         {
          "id": "a62db114-f655-403e-86ce-501bd35b4130",
          "comment": "",
          "command": "executeScript",
          "target": "return ${x}[0] + 2",
          "targets": [],
          "value": "y"
        },
        {
          "id": "93db74e6-391f-445f-b61e-0e79130accf5",
          "comment": "",
          "command": "assert",
          "target": "y",
          "targets": [],
          "value": "3"
        }


        {
          "id": "31d73787-8d99-4fde-8b94-78dd0b8abe80",
          "comment": "",
          "command": "executeScript",
          "target": "return {a:1}",
          "targets": [],
          "value": "x"
        }, {
          "id": "b5b2b0e4-0121-481e-97a0-76c64049683e",
          "comment": "",
          "command": "executeScript",
          "target": "return ${x}.a + 2",
          "targets": [],
          "value": "y"
        }, {
          "id": "0b54ce0f-4189-4098-8298-7850223a58d5",
          "comment": "",
          "command": "assert",
          "target": "y",
          "targets": [],
          "value": "3"
        }


        {
        "id": "2db19339-f720-44eb-8f0d-7b2e8868972e",
        "name": "execute script primitives",
        "commands": [{
          "id": "fff22deb-92ef-4e85-8cef-96b675cb6179",
          "comment": "",
          "command": "executeScript",
          "target": "return \"test\"",
          "targets": [],
          "value": "string"
        }, {
          "id": "64ff1187-0ee1-4aea-954d-ff0fb0b3effd",
          "comment": "",
          "command": "assert",
          "target": "string",
          "targets": [],
          "value": "test"
        }, {
          "id": "e68361d0-92a4-4e0b-8ad6-6f661a9eafb8",
          "comment": "",
          "command": "executeScript",
          "target": "return 3.14",
          "targets": [],
          "value": "float"
        }, {
          "id": "d900a277-6046-403e-b9a4-f0a88a4a419e",
          "comment": "",
          "command": "assert",
          "target": "float",
          "targets": [],
          "value": "3.14"
        }, {
          "id": "ce5cf714-7fa1-4839-9e97-df75aeb1e91f",
          "comment": "",
          "command": "executeScript",
          "target": "return true",
          "targets": [],
          "value": "bool"
        }, {
          "id": "d727b32c-73d3-4695-8b92-74871da374ab",
          "comment": "",
          "command": "assert",
          "target": "bool",
          "targets": [],
          "value": "true"
        }
        :return:
        """
        pass

    def executeAsyncScript(self):
        """
        {
          "id": "e804bce2-5c87-47df-9a06-9b69f531418b",
          "comment": "",
          "command": "executeAsyncScript",
          "target": "return new Promise((r) => {setTimeout(() => {r(\"async\")}, 500)})",
          "targets": [],
          "value": "async"
        }
        :return:
        """
        pass

    def forEach(self):
        pass

    def If(self):
        """
        {
          "id": "80e0bc3a-0fde-4238-9083-b6a0cac7c251",
          "comment": "",
          "command": "elseIf",
          "target": "${myVar} === \"b\"",
          "targets": [],
          "value": ""
        }
        关键字：需要大写
        :return:
        """
        pass

    def mouseDown(self):
        pass

    def mouseDownAt(self):
        """
        {
          "id": "fd7e2a08-9aa7-470d-8c32-d4f767467f1f",
          "comment": "",
          "command": "mouseDownAt",
          "target": "id=a",
          "targets": [],
          "value": "0,0"
        }
        :return:
        """
        pass

    def mouseMoveAt(self):
        pass

    def mouseOut(self):
        """
        {
      "id": "43b27b43-8ea8-47db-8f4f-5ffc494ab37f",
      "comment": "",
      "command": "mouseOut",
      "target": "id=a",
      "targets": [
        ["id=a", "id"],
        ["css=#a", "css:finder"],
        ["css=#a", "css"],
        ["xpath=//div[@id='a']", "xpath:attributes"],
        ["xpath=//div", "xpath:position"]
      ],
      "value": ""
    }
        :return:
        """
        pass

    def mouseOver(self):
        """
        {
          "id": "76b67130-be6f-477b-ba9c-7c43b76d641f",
          "comment": "",
          "command": "mouseOver",
          "target": "id=a",
          "targets": [],
          "value": ""
        }
        :return:
        """
        pass

    def mouseUp(self):
        pass

    def mouseUpAt(self):
        """
        {
          "id": "325fad52-86e2-4656-817c-a9f22a28ecfa",
          "comment": "",
          "command": "mouseUpAt",
          "target": "id=a",
          "targets": [],
          "value": "0,0"
        }
        :return:
        """
        pass

    def open(self):
        """
        {
          "id": "d94279f9-bf88-47c7-b339-a8d6e143f141",
          "comment": "",
          "command": "open",
          "target": "https://www.baidu.com/",
          "targets": [],
          "value": ""
        }
        :return:
        """
        """打开网站"""
        if self.testCommandTarget.startswith("/"):
            self.driver.get(self.testUrl + self.testCommandTarget)
        else:
            self.driver.get(self.testCommandTarget)

    def pause(self):
        pass

    def removeSelection(self):
        pass

    def repeatIf(self):
        pass

    def Run(self):
        """
        关键字：需要大写
        :return:
        """
        pass

    def runScript(self):
        pass

    def select(self):
        """
        {
          "id": "34c991ee-db67-4e15-be7d-9f84be17bdda",
          "comment": "",
          "command": "select",
          "target": "id=select",
          "targets": [],
          "value": "${label}"
        }
        :return:
        """
        pass

    def selectFrame(self):

        """
         {
          "command": "selectFrame",
          "id": "4f6cdc2b-5b8b-4755-ae0f-151220619870",
          "target": "index=0",
          "value": ""
        },
        {
          "command": "click",
          "target": "css=h2:nth-child(5)",
          "value": "",
          "insertBeforeLastCommand": false,
          "frameLocation": "root/0",
          "id": "6ce20c92-1335-4fb7-bc75-75a873f26a34",
          "targets": [
            [
              "css=h2:nth-child(5)",
              "css:finder"
            ],
            [
              "xpath=//h2[contains(.,'UAAG 1.0 Requirement')]",
              "xpath:innerText"
            ]
          ]
        },
        {
          "command": "click",
          "target": "css=h2:nth-child(5)",
          "value": "",
          "insertBeforeLastCommand": false,
          "frameLocation": "root/0",
          "id": "6078cfd9-9fb6-4205-bb05-66b54213c1b9",
          "targets": [
            [
              "css=h2:nth-child(5)",
              "css:finder"
            ],
            [
              "xpath=//h2[contains(.,'UAAG 1.0 Requirement')]",
              "xpath:innerText"
            ]
          ]
        },
        {
          "command": "click",
          "target": "css=.checkpoint:nth-child(2)",
          "value": "",
          "insertBeforeLastCommand": false,
          "frameLocation": "root/0",
          "id": "83c206c7-5bfb-4d2b-8c54-204c9f09989d",
          "targets": [
            [
              "css=.checkpoint:nth-child(2)",
              "css:finder"
            ]
          ]
        },
        {
          "command": "selectFrame",
          "id": "e6f49a0d-81e4-4083-9fb4-76c837fb51e8",
          "target": "relative=parent",
          "value": ""
        },
        {
          "command": "selectFrame",
          "id": "8cd601f3-da01-4651-9c33-295ecf4ced7b",
          "target": "index=1",
          "value": ""
        },
        {
          "command": "click",
          "target": "css=html",
          "value": "",
          "insertBeforeLastCommand": false,
          "frameLocation": "root/1",
          "id": "36f6497f-5187-4b8b-b64a-31c283ec7e6b",
          "targets": [
            [
              "css=html",
              "css:finder"
            ],
            [
              "xpath=//html[contains(.,'Test Link 1')]",
              "xpath:innerText"
            ]
          ]
        },
        {
          "command": "click",
          "target": "css=html",
          "value": "",
          "insertBeforeLastCommand": false,
          "frameLocation": "root/1",
          "id": "96a96789-02d4-433e-addf-dd0c2fa5e249",
          "targets": [
            [
              "css=html",
              "css:finder"
            ],
            [
              "xpath=//html[contains(.,'Test Link 1')]",
              "xpath:innerText"
            ]
          ]
        },
        {
          "command": "click",
          "target": "linkText=Test Link 1",
          "value": "",
          "insertBeforeLastCommand": false,
          "frameLocation": "root/1",
          "id": "50bb47da-a84e-4fb6-b1a9-6eb8b9340960",
          "targets": [
            [
              "linkText=Test Link 1",
              "linkText"
            ],
            [
              "css=a",
              "css:finder"
            ],
            [
              "xpath=(//a[contains(text(),'Test Link 1')])[1]",
              "xpath:link"
            ],
            [
              "xpath=(//a[contains(@href, '../action/return.html')])[1]",
              "xpath:href"
            ],
            [
              "xpath=//a[contains(.,'Test Link 1')]",
              "xpath:innerText"
            ]
          ]
        },
        {
          "command": "click",
          "target": "css=input",
          "value": "",
          "insertBeforeLastCommand": false,
          "frameLocation": "root/1",
          "id": "076cc6e1-9c4e-4fd2-abcf-3eb692bfb9e1",
          "targets": [
            [
              "css=input",
              "css:finder"
            ],
            [
              "xpath=(//input[@value='Go Back'])[1]",
              "xpath:attributes"
            ]
          ]
        },
        {
          "command": "selectFrame",
          "id": "d369feb7-b854-49e2-b795-483f8e2b8b0b",
          "target": "relative=parent",
          "value": ""
        },
        {
          "command": "selectFrame",
          "id": "5ad2596d-5c2b-4697-bcb3-b72dd86bb1c2",
          "target": "index=2",
          "value": ""
        },
        {
          "command": "click",
          "target": "linkText=Test Link 2",
          "value": "",
          "insertBeforeLastCommand": false,
          "frameLocation": "root/2",
          "id": "92063795-0c37-459c-b415-63180c5f4192",
          "targets": [
            [
              "linkText=Test Link 2",
              "linkText"
            ],
            [
              "css=a",
              "css:finder"
            ],
            [
              "xpath=(//a[contains(text(),'Test Link 2')])[1]",
              "xpath:link"
            ],
            [
              "xpath=(//a[contains(@href, '../action/return.html')])[1]",
              "xpath:href"
            ],
            [
              "xpath=//a[contains(.,'Test Link 2')]",
              "xpath:innerText"
            ]
          ]
        }
        :return:
        """
        pass

    def selectWindow(self):
        """
        {
          "id": "2bc8f837-bc71-4849-8c03-a3670124bcf1",
          "comment": "",
          "command": "selectWindow",
          "target": "handle=${root}",
          "targets": [],
          "value": ""
        }
        :return:
        """
        targetValue = self.template(self.testCommandTarget)
        logger.info(targetValue)
        handle, value = targetValue.split("=")
        value = self.template(value)
        logger.info(value)
        self.driver.switch_to.window(self.vars[value])

    def sendKeys(self):
        """
        {
          "id": "d8e4f66d-6af7-4065-8cec-763a6e03c9d4",
          "comment": "",
          "command": "sendKeys",
          "target": "id=kw",
          "targets": [
            ["id=kw", "id"],
            ["name=wd", "name"],
            ["css=#kw", "css:finder"],
            ["xpath=//input[@id='kw']", "xpath:attributes"],
            ["xpath=//form[@id='form']/span/input", "xpath:idRelative"],
            ["xpath=//span/input", "xpath:position"]
          ],
          "value": "${KEY_ENTER}"
        }
        :return:
        """
        by, value = self.testCommandTarget.split("=")
        # 判断是否为按键
        if self.testCommandValue.startswith('$'):
            keyVale = self.testCommandValue.split("_")[-1][0:-1]
            logger.info("按下按键：" + keyVale)
            if hasattr(self.ele, by):
                fun = getattr(self.ele, by)
                targetEle = fun(value)
                key = getattr(Keys, keyVale)
                Actions(targetEle).sendKeys(key)

    def setSpeed(self):
        """设置速度"""
        pass

    def setWindowSize(self):
        """
        {
          "id": "394a8899-7d91-405f-9631-32d5a0b38b42",
          "comment": "",
          "command": "setWindowSize",
          "target": "1440x755",
          "targets": [],
          "value": ""
        }
        :return:
        """
        try:
            width, height = self.testCommandTarget.split('x')
        except Exception as e:
            width, height = 1440, 1080
        """设置浏览器尺寸"""
        self.driver.set_window_size(width=width, height=height)

    def store(self):
        """
        {
          "id": "48d4aacc-418b-4684-bfe8-cbb75356adbb",
          "comment": "",
          "command": "store",
          "target": "Two",
          "targets": [],
          "value": "label"
        }
        :return:
        """
        pass

    def storeAttribute(self):
        """
        {
          "id": "e3794da0-c506-4d85-a628-a8f6f92b12ce",
          "comment": "",
          "command": "storeAttribute",
          "target": "id=test-id-1@style",
          "targets": [],
          "value": "var1"
        }
        :return:
        """
        pass

    def storeJson(self):
        pass

    def storeText(self):
        pass

    def storeTitle(self):
        pass

    def storeValue(self):
        pass

    def storeWindowHandle(self):
        """
        {
          "id": "805fda03-a6ce-49cc-82f3-9e5fd9de76de",
          "comment": "",
          "command": "storeWindowHandle",
          "target": "root",
          "targets": [],
          "value": ""
        }
        :return:
        """
        # 存储当前窗口
        """此命令不能用"""
        logger.info(self.testCommandTarget)
        logger.info(self.driver.current_window_handle)
        self.vars[self.testCommandTarget] = self.driver.current_window_handle

        pass

    def storeXpathCount(self):
        """
        {
      "id": "3ca83da5-71ac-44cd-91b4-0dff477a2969",
      "comment": "",
      "command": "storeXpathCount",
      "target": "xpath=//span",
      "targets": [],
      "value": "span_count"
    },
        :return:
        """
        pass

    def submit(self):
        pass

    def times(self):
        pass

    def type(self):
        """
        {
          "id": "5177e17c-9241-4611-9576-6cc84003953d",
          "comment": "",
          "command": "type",
          "target": "id=kw",
          "targets": [
            ["id=kw", "id"],
            ["name=wd", "name"],
            ["css=#kw", "css:finder"],
            ["xpath=//input[@id='kw']", "xpath:attributes"],
            ["xpath=//form[@id='form']/span/input", "xpath:idRelative"],
            ["xpath=//span/input", "xpath:position"]
          ],
          "value": "demo"
        },
        {
          "id": "f1bb7ae5-d546-43d2-a910-489c39afb123",
          "comment": "",
          "command": "type",
          "target": "id=v",
          "targets": [],
          "value": "${sync}"
        }
        :return:
        """
        by, value = self.testCommandTarget.split("=")
        if hasattr(self.ele, by):
            fun = getattr(self.ele, by)
            targetEle = fun(value)
            Actions(targetEle).clear()
            valueValue = self.template(self.testCommandValue)
            Actions(targetEle).sendKeys(valueValue)

    def uncheck(self):
        """
        {
          "id": "ecc4ad19-5532-40fb-b33b-0afb0e8c9fe7",
          "comment": "",
          "command": "uncheck",
          "target": "id=f",
          "targets": [],
          "value": ""
        }
        :return:
        """
        pass

    def verify(self):
        pass

    def verifyChecked(self):
        pass

    def verifyEditable(self):
        pass

    def verifyElementPresent(self):
        pass

    def verifyElementNotPresent(self):
        pass

    def verifyNotChecked(self):
        pass

    def verifyNotEditable(self):
        pass

    def verifyNotSelectedValue(self):
        pass

    def verifyNotText(self):
        """
        {
          "id": "5d44c22b-bee6-4ee0-bb36-076db811c90a",
          "comment": "",
          "command": "assertNotText",
          "target": "id=b",
          "targets": [],
          "value": "not show alert"
        }, {
          "id": "02068205-16e4-495e-aed5-87cdab7e7487",
          "comment": "",
          "command": "verifyNotText",
          "target": "id=b",
          "targets": [],
          "value": "not show alert"
        }
        :return:
        """
        pass

    def verifySelectedLabel(self):
        """
        {
          "id": "71537b82-ff16-449e-8aa9-618ee22f5ccd",
          "comment": "",
          "command": "verifySelectedLabel",
          "target": "id=select",
          "targets": [],
          "value": "One"
        }
        :return:
        """
        pass

    def verifySelectedValue(self):
        pass

    def verifyText(self):
        """
        {
          "id": "8a202701-15f3-43c1-ab92-faee105450af",
          "comment": "",
          "command": "assertText",
          "target": "id=b",
          "targets": [],
          "value": "show alert"
        }, {
          "id": "9edb7147-7266-4b7f-8a91-a13fe4ad7180",
          "comment": "",
          "command": "verifyText",
          "target": "id=b",
          "targets": [],
          "value": "show alert"
        }
        :return:
        """
        pass

    def verifyTitle(self):
        pass

    def verifyValue(self):
        pass

    def waitForElementEditable(self):
        """
        {
          "id": "46e5ef5d-ec77-4e42-84de-96a4ac3ce172",
          "comment": "",
          "command": "waitForElementEditable",
          "target": "css=#input-example input",
          "targets": [],
          "value": "10000"
        }
        :return:
        """
        pass

    def waitForElementNotEditable(self):
        pass

    def waitForElementNotPresent(self):
        """
         {
          "command": "waitForElementNotPresent",
          "target": "css=.dne",
          "value": "",
          "id": "d341e173-b4f8-4645-b25d-1b58f55ef371"
        }
        :return:
        """
        pass

    def waitForElementNotVisible(self):
        pass

    def waitForElementPresent(self):
        pass

    def waitForElementVisible(self):
        pass

    def waitForText(self):
        """
        {
          "id": "fa9bae47-4a7e-4e92-9e02-e6863c13aaf1",
          "comment": "",
          "command": "waitForText",
          "target": "id=a",
          "targets": [],
          "value": "down"
        }
        :return:
        """
        pass

    def webdriverAnswerOnVisiblePrompt(self):
        pass

    def webdriverChooseCancelOnVisibleConfirmation(self):
        pass

    def webdriverChooseCancelOnVisiblePrompt(self):
        pass

    def webdriverChooseOkOnVisibleConfirmation(self):
        pass

    def While(self):
        """
        关键字：需要大写
        :return:
        """
        pass

    # def back(self):
    #     """后退"""
    #     self.driver.back()
    #
    # def forward(self):
    #     """前进"""
    #     self.driver.forward()
    #
    # def refresh(self):
    #     """刷新"""
    #     self.driver.refresh()
    #
    # @property
    # def current_window_handle(self):
    #     """获取当前窗口句柄"""
    #     return self.driver.current_window_handle
    #
    #
    # @property
    # def window_handles(self):
    #     """获取当前标签页句柄"""
    #     return self.driver.window_handles
